package com.shiroa.common;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.shiroa.entity.vo.LoginUser;
import com.shiroa.redis.RedisUtil;
import lombok.SneakyThrows;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Aspect
@Component
public class RequiredPermsAspect {
    @Autowired
    private RedisUtil redisUtils;
    @Around(value = "@annotation(com.shiroa.common.RequiredPerms)")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable{
        MethodSignature methodSignature=(MethodSignature) joinPoint.getSignature();
        RequiredPerms annotation=methodSignature.getMethod().getDeclaredAnnotation(RequiredPerms.class);
        if (checkPerms(annotation.value())){
            return joinPoint.proceed();
        }
        throw new RuntimeException("无权访问");
    }

    @SneakyThrows
    private boolean checkPerms(String value) {
        ServletRequestAttributes servletRequestAttributes= (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String token=servletRequestAttributes.getRequest().getHeader("token");
        String json=redisUtils.get(token);
        if (StringUtils.hasText(json)){
            LoginUser loginUser=new ObjectMapper().readValue(json,LoginUser.class);
            loginUser.getPermsList().contains(value);
        }
        return false;
    }
}
